from flask import Flask, request, jsonify
from utils.musicAPi import wyy
from utils.custom_response import C_Response

app = Flask(__name__)


@app.route("/api/v1/get_song", methods=["get"], endpoint="get_song")
def get_song():
    '''获取到歌曲的播放地址'''
    res = C_Response(0, "获取成功")
    # 接口格式为127.0.0.1:5000/api/v1/get_song?song_id=1
    song_id = request.args.get("song_id", "zxc")
    try:
        song_id = int(song_id)
        # 调用网易云的api获取数据
        mp3_url = wyy.get_Songs(song_id)
        if mp3_url:
            res.data = mp3_url
        else:
            res.status = -2
            res.message = "歌曲id不存在"
    except ValueError:
        res.status = -1
        res.message = "参数违法"
    return jsonify(res.get_dict())


@app.route("/api/v1/search_keyword", methods=["get"], endpoint="search_keyword")
def search_keyword():
    # api格式为127.0.0.1:5000/api/v1/search_keyword?keyword=?&offset=?   offset为30的倍数
    res = C_Response(0, "获取成功")
    kw = request.args.get("keyword", None)
    offset = request.args.get("offset", "0")
    if not kw or not offset.isdigit():
        res.status = -1
        res.message = "参数违法"
        return jsonify(res.get_dict())

    offset = int(offset)
    results = wyy.search_KeyWord(kw, offset)
    res.data = results
    return jsonify(res.get_dict())


@app.route("/api/v1/get_comment", methods=["get"], endpoint="get_comment")
def get_comment():
    # api格式为127.0.0.1:5000/api/v1/get_comment?song_id=?offset=?   # offset 为20倍数
    res = C_Response(0, "ok")
    song_id = request.args.get("song_id")
    offset = request.args.get("offset", "0")
    if not offset.isdigit():
        res.status = -1
        res.message = "参数非法"
        return jsonify(res.get_dict())
    if not song_id or not song_id.isdigit():
        res.status = -1
        res.message = "参数非法"
        return jsonify(res.get_dict())

    results = wyy.song_comment(song_id, offset)
    res.data = results
    return jsonify(res.get_dict())


if __name__ == '__main__':
    app.run(debug=True)
    
